from Login import *
import requests
import json
import platform

##############
#author:yunli#
##############

class CSCommunication():

    def __init__(self):
        pass

    def Login(self, username, password):   # 进行登录操作，成功则返回1，失败返回0
        req = requests.post('http://192.168.2.145:8080/user/clientlogin',
                            data={
                                'username': username,
                                'password': password
                            })
        jsonObject = req.json()  # 接收返回的json数据
        print(jsonObject)  # 返回字节形式
        print(jsonObject['msg'])  # json属性获取
        if jsonObject['code'] == 200:
            return 1
        else:
            return 0

    def DeviceRegist(self, HostInformation):  # 传输设备注册的信息
        HostInfoJson = json.dumps(HostInformation)
        # HostInfoJson["hostId"] =
        # 10.133.63.245:8080/login.html
        # 将本机已获取的设备信息通过host/insert接口传输到服务端数据库中，新增一个设备
        regist = requests.post('http://192.168.2.145:8080/host/insert',
                               headers={'Content-Type': 'application/json;charset=utf-8'},
                               data=HostInfoJson)
        jsonObject = regist.json()
        print(jsonObject)
        print(jsonObject['msg'])
        if jsonObject['code'] == 200:
            print("设备注册成功.")
        else:
            print("error")

        print(HostInfoJson)

        pass

    # def CheckOutput(self):
    #     pass

    def GetMission(self):   # 获取未执行的任务
        # 从服务端获取任务列表，并根据hostid确定当前设备任务
        task = requests.get("http://192.168.2.145:8080/task/selectAll")
        host = requests.get("http://192.168.2.145:8080/host/findhostlist")
        content = host.json()
        hostName = platform.node()
        task_result = []
        for i in content:
            if i["hostName"] == hostName:
                hostId = i["hostId"]
        # print(task.json())

        # 获取任务列表之后，根据其中各核查项的状态确定是否进行核查
        for i in task.json()['list']:
            num = i['id']
            task_info = []
            task_list = []
            task_host = i['hostid']
            if hostId == task_host:
                task_list.append(num)
                # 判定任务状态，若为0则进行核查，为1则跳过
                if i['status'] == 1:
                    continue
                elif i['status'] == 0:
                    # 判定核查项状态，为1则对该项进行核查，为0则跳过
                    if i['hostinfo'] == 1:
                        task_info.append('主机信息核查')
                    if i['gpedit'] == 1:
                        task_info.append('安全策略核查')
                    if i['patchinfo'] == 1:
                        task_info.append('补丁信息核查')
                    if i['netinfo'] == 1:
                        task_info.append('网络信息核查')
                    if i['backdoor'] == 1:
                        task_info.append('后门核查')
                    if i['selfstart'] == 1:
                        task_info.append('自启动项核查')
                    if i['service'] == 1:
                        task_info.append('服务项核查')
                task_list.append(task_info)

            task_result.append(task_list)
            # print(task_result)

        return task_result

        '''与服务器端通信，返回一个列表，形式大概为[[任务一的内容],[任务二的内容],....]'''

        '''
        服务器端发来信息数字对应的检测项目：
        0.'主机信息核查' 1.'安全策略核查' 2.'补丁信息核查' 3.'网络信息核查' 4.'后门核查' 5.'自启动项核查' 6.服务项核查'''

    def SendOutPut(self, id, Result):  # 向服务器发送检测结果
        send_msg = []
        # print(Result)
        send_msg.append(id)
        send_msg.append(Result)

        id_post = requests.post('http://192.168.2.145:8080/task/pushTask',
                                data={
                                    "id": id
                                })
        jsonObject = id_post.json()  # 接收返回的json数据
        print(jsonObject)  # 返回字节形式
        print(jsonObject['msg'])  # json属性获取
        if jsonObject['code'] == 200:
            print("任务状态更新成功")
        else:
            print("任务状态更新失败")
        print(send_msg)
        send_info_list = []
        for i in range(len(Result)):
            send_info = {}
            # send_msg.append(id)
            send_info["indexname"] = Result[i][1]
            send_info["currentval"] = Result[i][2]
            send_info["adviseval"] = Result[i][3]
            send_info["checktype"] = Result[i][0]
            send_info["taskid"] = id
            send_info_list.append(send_info)
        for i in range(len(send_info_list)):
            send_report = json.dumps(send_info_list[i])
            print(send_report)
            report = requests.post('http://192.168.2.145:8080/report/pushReport',
                                   headers={'Content-Type': 'application/json;charset=utf-8'},
                                   data=send_report)
            jsonObject = report.json()
            print(jsonObject)
            print(jsonObject['msg'])
            if jsonObject['code'] == 200:
                print("核查报告提交成功.")
            else:
                print("error")


            # send_msg.append(send_info)
            # send_msg = json.dumps(send_msg, ensure_ascii=False)
            # send_msg = send_msg.encode("gb2312").decode("gbk")
            # print(send_msg)

        # send_msg = json.dumps(send_msg, ensure_ascii=False)
        # send_msg = send_msg.encode("gb2312").decode("gbk")
        # print(send_msg)
        # out_info = json.dumps([id, Result], ensure_ascii=False)
        # out_info = out_info.encode("gb2312").decode("gbk")
        # print(out_info)



        '''检测结果输出大概格式：[任务id,[[第一个检测项，检测结果，加固建议],[第二个检测项，检测结果，加固建议],...]'''

if __name__ == '__main__':
    login = LoginStart()
    login.start()
